﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlDoiGiaHangBan : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (ViewState["flag"] == null)
            {
                //ViewState["flag"] = false;
                ClearAdd();
            }
            txtDate.Text = Session["workingday"].ToString();
            BindGridSearch(Session["sitecode"].ToString());
        }
        MessageBox.ShowOnPageLoad = false;
    }

    void ClearAdd()
    {
        txtSoNV.Text = "New";

        txtDate.Text = Session["workingday"].ToString();

        if (ViewState["KhoHangTemp"] != null)
        {
            ViewState["KhoHangTemp"] = null;

        }
        BindGridProduct();

        ViewState["flag"] = true;
        TabContainer1.ActiveTabIndex = 0;

        lblMsg.Text = "";
        lblMsg.Visible = false;
        btnDelete.Visible = false;
        btnSave.Text = "Lưu";
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();
        
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
      
    }
    public int CompareDate(string sdate1, string sdate2)
    {
        DateTime date1 = new DateTime(int.Parse(sdate1.Substring(6, 4)), int.Parse(sdate1.Substring(3, 2)), int.Parse(sdate1.Substring(0, 2)));
        DateTime date2 = new DateTime(int.Parse(sdate2.Substring(6, 4)), int.Parse(sdate2.Substring(3, 2)), int.Parse(sdate2.Substring(0, 2)));
        int result = DateTime.Compare(date1, date2);
        return result;

        //if (result < 0)
        //    relationship = "sdate1 is earlier than";
        //else if (result == 0)
        //    relationship = "is the same time as";
        //else
        //    relationship = "sdate 1 is later than";

    }
        
    protected void grvSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblSoNV = (Label)grv.FindControl("lblSoNV");

                DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getDetailChangePrice", CommandType.StoredProcedure,
                   new SqlParameter("@DocNo", lblSoNV.Text));
                txtSoNV.Text = db.Rows[0]["docno"].ToString();
                txtDate.Text = db.Rows[0]["DocDate"].ToString();

                ViewState["KhoHangTemp"] = db;

                grvProduct.DataSource = db;
                grvProduct.DataBind();

                grvSearch.DataSource = null;
                grvSearch.DataBind();

                ViewState["flag"] = false;
                TabContainer1.ActiveTabIndex = 0;
                
                lblMsg.Text = "";
                lblMsg.Visible = false;
                btnSave.Text = "Cập nhật";
                btnDelete.Visible = true;

            }
        }
        catch (Exception ex)
        {
          
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    //protected void txtMaHang_TextChanged(object sender, EventArgs e)
    //{
    //    dt = new ClassExecute.ClassExecute();
    //    try
    //    {
    //        string Chuoi = txtMaHang.Text;
    //        int index = Chuoi.IndexOf("|");
    //        txtMaHang.Text = Chuoi.Substring(0, index - 1);
    //        txtTenHang.Text = Chuoi.Substring(index + 2, Chuoi.Length - index - 2);
    //        txtOldPrice.Text = dt.GetDataDepend(str, "k_getPice", CommandType.StoredProcedure, ref error,
    //            new SqlParameter("@itemkey", txtMaHang.Text));
    //        txtNewPrice.Focus();

    //    }
    //    catch
    //    {
    //        return;
    //    }
    //}
    //protected void btAdd_Click(object sender, EventArgs e)
    //{
    //    UpdateGridProduct();
    //}
    //void UpdateGridProduct()
    //{
    //    DataTable table = new DataTable();
    //    if (ViewState["KhoHangTemp"] != null)
    //    {
    //        table = (DataTable)ViewState["KhoHangTemp"];
    //        foreach (DataRow dr in table.Rows)
    //        {
    //            if (dr[0].ToString() == txtMaHang.Text)
    //            {
    //                dr[3] = Double.Parse(txtNewPrice.Text);
    //                ViewState["KhoHangTemp"] = table;
    //                grvProduct.DataSource = ViewState["KhoHangTemp"];
    //                grvProduct.DataBind();
    //                return;
    //            }
    //        }

    //        DataRow row = table.NewRow();
    //        //Fill All Columns with Data
    //        row[0] = txtMaHang.Text;
    //        row[1] = txtTenHang.Text;
    //        row[2] = Double.Parse(txtOldPrice.Text);
    //        row[3] = Double.Parse(txtNewPrice.Text);

    //        table.Rows.Add(row);
    //    }
    //    else
    //    {


    //        DataColumn col1 = new DataColumn("Mã hàng");
    //        DataColumn col2 = new DataColumn("Tên hàng");
    //        DataColumn col3 = new DataColumn("Giá cũ");
    //        DataColumn col4 = new DataColumn("Giá mới");

    //        col1.DataType = System.Type.GetType("System.String");
    //        col2.DataType = System.Type.GetType("System.String");
    //        col3.DataType = System.Type.GetType("System.Double");
    //        col4.DataType = System.Type.GetType("System.Double");

    //        table.Columns.Add(col1);
    //        table.Columns.Add(col2);
    //        table.Columns.Add(col3);
    //        table.Columns.Add(col4);

    //        //Create a Row in the DataTable table
    //        DataRow row = table.NewRow();
    //        //Fill All Columns with Data
    //        row[col1] = txtMaHang.Text;
    //        row[col2] = txtTenHang.Text;
    //        row[col3] = Double.Parse(txtOldPrice.Text);
    //        row[col4] = Double.Parse(txtNewPrice.Text);

    //        table.Rows.Add(row);

    //        ViewState["KhoHangTemp"] = table;
    //    }
    //    grvProduct.DataSource = ViewState["KhoHangTemp"];
    //    grvProduct.DataBind();

    //    txtMaHang.Text = "";
    //    txtTenHang.Text = "";
    //    txtOldPrice.Text = "";
    //    txtNewPrice.Text = "";
    //    txtMaHang.Focus();
    //}
    protected void grvProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();
            TextBox txtGM = (TextBox)grvProduct.Rows[e.RowIndex].FindControl("txtGM");
            if ((txtGM.Text == "") || (txtGM.Text == "0"))
            {
                txtGM.Text = "1";
            }
            Double NewPrice = Double.Parse(txtGM.Text);
            DataTable table = new DataTable();
            table = (DataTable)ViewState["KhoHangTemp"];

            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == keys)
                {
                    dr[3] = NewPrice;
                    table.AcceptChanges();
                    ViewState["KhoHangTemp"] = table;

                    grvProduct.EditIndex = -1;
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                }
            }

        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTemp"] = table;
                grvProduct.EditIndex = -1;
                grvProduct.DataSource = ViewState["KhoHangTemp"];
                grvProduct.DataBind();
                return;
            }
            i++;
        }
    }
    protected void grvProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvProduct.EditIndex = -1;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void grvProduct_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvProduct.EditIndex = e.NewEditIndex;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    void BindGridSearch(string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getMasterChangePrice", CommandType.StoredProcedure,
                 new SqlParameter("@type", "F"),
                new SqlParameter("@siteCode", sitecode));
            grvSearch.DataSource = db;
            grvSearch.DataBind();
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvSearch.PageIndex = e.NewPageIndex;
        BindGridSearch(Session["sitecode"].ToString());
    }
    protected void ImgBtnRequest_Click(object sender, ImageClickEventArgs e)
    {

        BindGridSearch(Session["sitecode"].ToString());
    }
    void BindGridProduct()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getProductForChangePrice", CommandType.StoredProcedure,
            new SqlParameter("@sitecode", Session["sitecode"].ToString()));
        if (db.Rows.Count > 0)
        {
            grvProduct.DataSource = db;
            ViewState["KhoHangTemp"] = db;
        }
        else
        {
           
            grvProduct.DataSource = null;
        }
        grvProduct.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (grvProduct.Rows.Count > 0)
        {
            int checkkhoaso = CompareDate(txtDate.Text, Session["workingday"].ToString());
            if (checkkhoaso < 0)
            {
                //ShowMessageBox("Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString());
                lblMsg.Text = "Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString();
                lblMsg.Visible = true;
                txtDate.Focus();
            }
            else
            {
                dt = new ClassExecute.ClassExecute();
                try
                {

                    string docno = "";
                    if ((bool)ViewState["flag"])
                    {
                        docno = dt.GetDataDepend(str, "[k_getDocNoChangPrice]", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()));
                        ViewState["flag"] = true;
                    }
                    else
                    {
                        docno = txtSoNV.Text;
                    }
                    int i = 1;
                   
                    foreach (GridViewRow grv in grvProduct.Rows)
                    {
                        Label lblMaHang = (Label)grv.FindControl("lblMaHang");

                        Label lblGiaCu = (Label)grv.FindControl("lblGiaCu");
                        Label lblGiaMoi = (Label)grv.FindControl("lblGiaMoi");
                        if (float.Parse(lblGiaMoi.Text)!=float.Parse(lblGiaCu.Text))
                        {
                        bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_inssertNVChangePrice", ref error,
                            new SqlParameter("@itemkey", lblMaHang.Text),
                            new SqlParameter("@docno", docno),
                            new SqlParameter("@Type", "F"),
                            new SqlParameter("@docdate", txtDate.Text),
                            new SqlParameter("@stocprice", float.Parse(lblGiaMoi.Text)),
                            new SqlParameter("@stockcost", float.Parse(lblGiaCu.Text)),
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()),
                            new SqlParameter("@i", i));
                        }
                       
                        i++;
                    }

                   
                        if (ViewState["KhoHangTemp"] != null)
                        {
                            ViewState["KhoHangTemp"] = null;

                        }

                        grvProduct.DataSource = null;
                        grvProduct.DataBind();


                        txtDate.Text = Session["workingday"].ToString();
                        txtSoNV.Text = "";
                        txtDate.Text = "";


                        //ShowMessageBox("Nghiệp vụ đổi giá thành công");
                        lblMsg.Text = "Nghiệp vụ đổi giá thành công";
                        lblMsg.Visible = true;
                    
                }
                catch (Exception ex)
                {

                    string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
                }
            }
        }
        else
        {
            //ShowMessageBox("Nghiệp vụ chưa được khởi tạo");
            lblMsg.Text = "Nghiệp vụ chưa được khởi tạo";
            lblMsg.Visible = true;
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if ((txtSoNV.Text != "") && (txtSoNV.Text != null))
            {
                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_deleteChangeprice", ref error,
                     new SqlParameter("@DocNo", txtSoNV.Text));
                if (kq)
                {

                    grvProduct.DataSource = null;
                    grvProduct.DataBind();
                    if (ViewState["KhoHangTemp"] != null)
                    {
                        ViewState["KhoHangTemp"] = null;

                    }
                    txtSoNV.Text = "";


                    
                    //ShowMessageBox("Nghiệp vụ xóa thành công");
                    ClearAdd();
                    lblMsg.Text = "Nghiệp vụ xóa thành công";
                    lblMsg.Visible = true;
                }
                else
                {
                    //ShowMessageBox("Hệ thống đang bảo trì");
                    lblMsg.Text = "Hệ thống đang bảo trì";
                    lblMsg.Visible = true;
                }
            }
            else
            {
                //ShowMessageBox("Nghiệp vụ chưa được khởi tạo");
                lblMsg.Text = "Nghiệp vụ chưa được khởi tạo";
                lblMsg.Visible = true;
            }
        }
        catch (Exception ex)
        {
            //ShowMessageBox("Hệ thống đang bảo trì");
            lblMsg.Text = "Hệ thống đang bảo trì";
            lblMsg.Visible = true;
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   

    }
}